package com.rpframework.module.common.bottom.controller

import com.rpframework.module.common.bottom.enums.FileType
import com.rpframework.module.common.url.RequestDescription
import org.apache.commons.fileupload.FileItem
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * http://www.wangeditor.com/index.html
 * Created by 刘兴 on 2016/10/18.
 */
@Suppress("DEPRECATION")
@RequestMapping
@RequestDescription("wangEditor富文本")
@Controller
@ResponseBody
open class WangEditorController {
    @Autowired
    lateinit var fileUploadController: FileUploadController

    @RequestMapping
    open fun uploadFile(file: MultipartFile, type: FileType?, request: HttpServletRequest) = try {
        fileUploadController.batch(arrayOf(file), type, request).data[0]
    } catch (e: Exception) {
        e.printStackTrace()
        "error|上传文件失败,服务器端错误"
    }!!

    @Suppress("UNCHECKED_CAST")
    @RequestMapping
    open fun uploadFileV2(request: HttpServletRequest, response: HttpServletResponse) {
        val path = request.getRealPath("/image")
        val file = File(path)
        if (!file.exists())
            file.mkdirs()
        var fileName = ""// 文件名称

        /**上传文件处理内容**/
        val factory = DiskFileItemFactory()
        val sfu = ServletFileUpload(factory)
        sfu.headerEncoding = "UTF-8" // 处理中文问题
        sfu.sizeMax = 1024 * 1024 // 限制文件大小
        try {
            val fileItems = sfu.parseRequest(request) as List<FileItem> // 解码请求
            for (fi in fileItems) {
                fileName = UUID.randomUUID().toString() + fi.name.substring(fi.name.lastIndexOf("."), fi.name.length)
                fi.write(File(path, fileName))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //获取图片url地址
        val imgUrl = "http://localhost:8080/wang_editor_demo/image/" + fileName
        response.contentType = "text/text;charset=utf-8"
        val out = response.writer
        out.print(imgUrl)  //返回url地址
        out.flush()
        out.close()
    }
}